package com.test.aop;

import com.hustcad.plm.pdm.partbom.dto.ObjectSaveAsDTO;
import com.hustcad.plm.pdm.user.model.vo.domain.DomainVO;
import com.test.mapper.CustomPartMapper;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigInteger;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Aspect
@Component
public class AroundService {

    @Resource
    CustomPartMapper customPartMapper;

    @Around(value = "execution(* com.hustcad.plm.pdm.user.service.TyplmDomainService.getDomainByParent(..))")
    public List<DomainVO> around(ProceedingJoinPoint pjp) throws Throwable {
        log.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>   around start");
        List<DomainVO> list = (List<DomainVO>) pjp.proceed();
        // 按照创建时间排序
        list = list.stream().sorted(Comparator.comparing(DomainVO::getCreatestamp)).collect(Collectors.toList());
        log.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>   around end");
        return list;
    }

    private final static String[] REMOVE_IBA_NAME = new String[]{"DESIGN_SOURCE", "MATERIAL"};

    @Around(value = "execution(* com.hustcad.plm.pdm.partbom.service.impl.saveas.TyplmSaveAsServiceImpl.saveAsInsertDB(..))")
    public Object afterSaveAsInsertDB(ProceedingJoinPoint pjp) throws Throwable {
        // 获取参数值
        Object[] args = pjp.getArgs();

        // 获取参数名称和类型
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        String[] paramNames = signature.getParameterNames();
        Class<?>[] paramTypes = signature.getParameterTypes();

        // 遍历参数信息
        for (int i = 0; i < args.length; i++) {
            System.out.println("参数名: " + paramNames[i]);
            System.out.println("参数类型: " + paramTypes[i].getName());
            System.out.println("参数值: " + args[i]);
        }
        Object proceed = pjp.proceed();
        List<ObjectSaveAsDTO> objectSaveAsList = (List<ObjectSaveAsDTO>) args[1];
        List<BigInteger> oidList = objectSaveAsList.stream()
                .map(ObjectSaveAsDTO::getOid).collect(Collectors.toList());
        log.info("objectSaveAsList::getOid=============>" + oidList.stream().map(BigInteger::toString)
                .collect(Collectors.joining(",")));
        int index = customPartMapper.removeIBAValue(oidList, REMOVE_IBA_NAME);
        log.info("objectSaveAsList::removeIBAValue============>" + index);
        return proceed;
    }
}
